/**
 * 
 * import { usePolling } from "@/views/hooks/usePolling";
 * const { setTimer } = usePolling();
 * 
 	setTimer(getInventorySyncGetSchedule, { batchId: data }, ({ completedNum, isCompleted, totalNum }) => {
		if (isCompleted) {
			console.log("isCompleted");
			setVisible("ResultModal");
			setResult({ total: totalNum, success: completedNum, failed: totalNum - completedNum });
			return true; // 返回 true ，轮询结束
		} else {
			console.log("setPercent");
			setPercent(((completedNum / totalNum) * 100).toFixed());
			return false;// 返回 false ，开启下一轮询
		}
	});
	
 * @returns 
 */

import { useState } from "react";
import { message } from "antd";
export const usePolling = (t = 3000) => {
	const __r = "timer" + String(new Date().getTime() + Math.random()).replace(".", "");
	const [r] = useState(__r);
	window[r] = null;
	/**
	 *
	 * @param {*} API
	 * @param {*} API_DATA
	 * @param {*} finishFn (data)=>boolean true 已完成； false 下一步
	 */
	function setTimer(API, API_DATA, finishFn, errFn) {
		API(API_DATA)
			.then(({ success, data, msg: msg1, message: msg2 }) => {
				console.log(success, data);
				if (success) {
					if (finishFn) {
						const txt = msg1 || msg2 || "查询任务进度成功";
						if (!finishFn({ success, message: txt, ...data })) {
							window[r] = setTimeout(() => {
								console.log("setTimeout", window[r]);
								window[r] && clearTimeout(window[r]);
								setTimer(API, API_DATA, finishFn, errFn);
							}, t);
						}
					}
				} else {
					console.log("查询任务进度失败1", data);
					const txt = msg1 || msg2 || "查询任务进度失败";
					message.warning(txt);
					if (errFn) {
						errFn(txt);
					} else {
						finishFn({ success: false, message: txt });
					}
				}
			})
			.catch(err => {
				console.log("查询任务进度失败2", err);
				const txt = "接口错误，查询任务进度失败";
				message.warning(txt);
				if (errFn) {
					errFn(txt);
				} else {
					finishFn({ success: false, message: txt });
				}
			});
	}

	const clearTimer = () => {
		window[r] && clearTimeout(window[r]);
	};
	return { setTimer, clearTimer, timer: window[r], r };
};
